<?php

class ContactController extends Controllers_BaseContent
{
	private $factoryForm = null;
	
    public function init() {
    	parent::init();
    	
    	$this->setFactoryForm(Manager::getFactoryForm());
        $this->view->contactForm = null;
        $this->view->isSent = false;
        $this->view->message = "";
    }

    public function indexAction() {
        $contactForm = $this->getFactoryForm()->getContactForm();
        $contactForm
        ->setName('contactForm')
		->setAction("")
		->setMethod('POST')
		->setAttrib('id', 'contactForm');
		
        $this->view->contactForm = $contactForm;
        
        if ($this->_request->isPost()) {
            $formContactData = $this->_request->getPost();
            if ($contactForm->isValid($formContactData)) {
            	$this->processMessage($formContactData);
            } else {
            	// Vide le champ du captcha
            	$formContactData['captchaInput'] = "";
            	// Correction bug dojo editor
            	if (is_array($formContactData['message']) && array_key_exists('Editor', $formContactData['message'])) {
            		$formContactData['message'] = $formContactData['message']['Editor'];
            	} 
                $contactForm->populate($formContactData);
            }
        }
    }
    
    public function sentAction() {
    }
    
    private function processMessage($formContactData) {
    	$this->saveMessage($formContactData);
    	$this->sendMessage($formContactData);
    	$this->_redirect($this->view->reformatUrl(array('controller' => 'contact', 'action' => 'sent')));
    }
    
    private function saveMessage($formContactData) {
    }
    
    private function sendMessage($formContactData) {
		$options = $this->getInvokeArg('bootstrap')->getOptions();
    	$emailRecipient = $options['contact']['email'];
    	$nameRecipient = $options['contact']['name'];
    	
    	$mail = new Zend_Mail($options['app']['charset']);
		$mail
		->setBodyText($formContactData['message'])
    	->setFrom($formContactData['email'], $formContactData['prenom'].' '.$formContactData['nom'])
    	->addTo($emailRecipient, $nameRecipient)
    	->setSubject($formContactData['objet'])
    	->send();
    }

	private function getFactoryForm() {
		return $this->factoryForm;
	}

	private function setFactoryForm(Factory_FactoryForm $factoryForm) {
		$this->factoryForm = $factoryForm;
	}

}



